import { RbacUserRoleType, RbacUserType } from '@/data/auth/admin';
import { PageParams } from '@/data/result';
import { StatusValueEnum } from '@/enums';
import { useTenants } from '@/hooks/auth/useTenants';
import AddModal from '@/pages/auth/rbacUser/components/AddModal';
import UpdateModal from '@/pages/auth/rbacUser/components/UpdateModal';
import { tablePage } from '@/services/data';
import { handleAdd, handleRemoveList, handleUpdate } from '@/services/handle';
import { PlusOutlined, UserOutlined } from '@ant-design/icons';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import { Avatar, Button, Drawer } from 'antd';
import React, { useRef, useState } from 'react';
import { default as RoleTags } from './components/RoleTags';

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<RbacUserType>();
  const [selectedRowsState, setSelectedRows] = useState<RbacUserType[]>([]);

  const { allTenantValueEnum } = useTenants();

  // @ts-ignore
  const columns: ProColumns<RbacUserRoleType>[] = [
    {
      title: '租户',
      dataIndex: 'tenantId',
      valueEnum: allTenantValueEnum,
    },
    {
      title: '管理员ID',
      dataIndex: 'id',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: StatusValueEnum,
    },
    {
      title: '角色',
      dataIndex: 'roleIds',
      render: (dom, entity) => <RoleTags roleIds={entity?.roleIds} />,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      hideInSearch: true,
      render: (dom, entity) => <Avatar src={entity.avatar} size={64} icon={<UserOutlined />} />,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '姓名',
      dataIndex: 'realName',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          更新
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<RbacUserRoleType, PageParams>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(data) => tablePage('/system/rbacUser/rolePage', data)}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemoveList('/system/rbacUser', selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <AddModal
        onSubmit={async (value) => {
          const success = await handleAdd('/system/rbacUser', value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        visible={createModalVisible}
      />
      <UpdateModal
        onSubmit={async (value) => {
          const success = await handleUpdate('/system/rbacUser', value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.username && (
          <ProDescriptions<RbacUserType>
            column={1}
            title={currentRow?.username}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.username,
            }}
            columns={columns as ProDescriptionsItemProps<RbacUserType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
